#!/usr/bin/python
# -*- encoding: utf-8 -*-
'''
@File    :   4server.py
@Time    :   2020/06/25 02:43:42
@Author  :   Malygos_l 
@Version :   1.0
@Contact :   751756061@qq.com
@WebSite :   www.gitee.com/malygos_l
'''
# Start typing your code from here
'''
多人聊天
'''
import socket
import get
import threading
import os


#封装
class ChatSever:
    def __init__(self):
        self.sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.addr = (get.get_ip(), 8888)
        self.users = {}

    def start_sever(self):
        try:
            self.sk.bind(self.addr)
        except Exception as e:
            print(e)
        self.sk.listen(5)
        print("服务器已开启...")
        print("在空白处输入stop sever并回车，来关闭服务器")

        self.accept_cont()

    def accept_cont(self):
        while True:
            s, addr = self.sk.accept()
            self.users[addr] = s
            number = len(self.users)
            print("用户{}连接成功！现在共有{}位用户".format(addr, number))

            threading.Thread(target=self.recv_send, args=(s, addr)).start()

    def recv_send(self, sk, addr):
        while True:
            try:
                response = sk.recv(4096).decode("gbk")
                msg = "{}用户{}发来消息：{}".format(get.get_time(), addr, response)

                for client in self.users.values():
                    client.send(msg.encode("gbk"))
            except ConnectionResetError:
                print("用户{}已经退出聊天！".format(addr))
                self.users.pop(addr)
                break

    def close_sever(self):
        for client in self.users.values():
            client.close()
        self.sk.close()
        os._exit(0)


if __name__ == "__main__":
    sever = ChatSever()
    sever.start_sever()
    while True:
        cmd = input()
        if cmd == "stop sever":
            sever.close_sever()
        else:
            print("输入命令无效，请重新输入！")